<template>
  <el-form :inline="true" class="demo-form-inline count">
    <el-form-item label="年份:" style="width: 195px">
      <el-select v-model="year" placeholder="选择年份">
        <el-option v-for="y in availableYears" :key="y" :label="y" :value="y"/>
      </el-select>
    </el-form-item>
    <el-form-item label="月份:" style="width: 195px">
      <el-select v-model="month" placeholder="选择月份">
        <el-option v-for="m in availableMonths" :key="m" :label="m" :value="m"/>
      </el-select>
    </el-form-item>
    <el-form-item style="margin-right: 0">
      <div style="display: flex; align-items: center;">
        <span style="width: 80px">
          <el-icon style="color: #19DE16;font-size: 18px; margin-right: 8px"><Select /></el-icon>正常
        </span>
        <span style="width: 110px">
          <el-icon style="color:#F3A21E;font-size: 18px; margin-right: 8px"><SemiSelect /></el-icon>迟到或早退
        </span>
        <span style="width: 80px">
          <el-icon style="color: red;font-size: 18px; margin-right: 8px"><CloseBold /></el-icon>旷工
        </span>
        <span style="width: 80px">
          <el-icon style="color: blue;font-size: 18px; margin-right: 8px"><Checked /></el-icon>请假
        </span>
      </div>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" border style="height: 68vh; overflow: auto;" class="attendanceClass">
    <el-table-column label="学生姓名" fixed="left" align="center">
      <template #default="scope">
        <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ scope.row.name }}</span>
      </template>
    </el-table-column>
    <!-- 动态生成一个月内每一天的列 -->
    <template v-for="day in dayInMonth" :key="day">
      <el-table-column :label="day" width="38px" align="center"  >
        <template #default="scope">
          <el-icon :style="{ color: getColor(scope.row, day) }">
            <component :is="getIcon(scope.row, day)"/>
          </el-icon>
        </template>
      </el-table-column>
    </template>
  </el-table>
</template>

<script setup>
import axios from "@/axios/index.js";
import { computed, onMounted, ref } from "vue";

import {Checked, CloseBold, Select, SemiSelect} from "@element-plus/icons-vue";
import { reactive } from "@vue/reactivity";
import { useRouter } from "vue-router";

let id = ref('');
let tableData = ref([]);
let loading = ref(true);
let formData = reactive({
  classId: '',
});

const router = useRouter();
// 当前选择的年份和月份
let year = ref(new Date().getFullYear());
let month = ref(new Date().getMonth() + 1);
// 可用的年份和月份范围
const currentDate = new Date();
const startYear = 2020;
const endYear = currentDate.getFullYear();
const availableYears = Array.from({ length: endYear - startYear + 1 }, (_, i) => startYear + i);
const availableMonths = Array.from({ length: 12 }, (_, i) => i + 1);

onMounted(async () => {
  const { classId } = router.currentRoute.value.query;
  formData.classId = classId;
  loadTableData();
});

function loadTableData() {
  loading.value = true;
  axios.get("/student/selectAttendance", {
    params: {
      classId: formData.classId,
      year: year.value,
      month: month.value,
    },
  }).then((resp) => {
    loading.value = false;
    tableData.value = resp.data.data;
    tableData.value.forEach((item) =>{
      item.attendance.forEach((attendance) => {
        // attendance.attendanceDate = attendance.attendanceDate.split("-");
        if (attendance.attendanceDate != null){
          attendance.attendanceDate = attendance.attendanceDate.split("-");
        }
      })
    })
  });
}

// 计算当前月份的天数
let dayInMonth = computed(() => {
  if (!year.value ||!month.value) return [];

  let date = new Date(year.value, month.value - 1);
  let daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  return Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString());
});

function getColor(row, day) {
  const attendanceList = row.attendance || [];
  const attendanceDate = new Date(year.value, month.value - 1, day);
  if (isLegalHolidayOrWeekend(attendanceDate)) {
    return 'white';
  }
  // const matchingAttendance = attendanceList.find(att => {
  //   const [attYear, attMonth, attDay] = att.attendanceDate;
  //   return new Date(attYear, attMonth - 1, attDay).getTime() === attendanceDate.getTime();
  // });
  const matchingAttendance = attendanceList.find(att => {
    if (att.attendanceDate != null){
      const [attYear, attMonth, attDay] = att.attendanceDate;
      return new Date(attYear, attMonth - 1, attDay).getTime() === attendanceDate.getTime();
    }
  })


  if (matchingAttendance) {
    switch (matchingAttendance.attendanceStatus) {
      case 1:
        return "#2EC62B";
      case 0:
        return "#F3A21E";
      case 3:
        return "blue";
      default:
        return "red";
    }
  } else {
    return "red";
  }
}

function getIcon(row, day) {
  const color = getColor(row, day);
  return color === "#2EC62B"? Select : (color === "#F3A21E"? SemiSelect : (color === "blue"? Checked : CloseBold));
}

function isLegalHolidayOrWeekend(date) {
  // 判断是否是周六或周日
  const dayOfWeek = date.getDay();
  if (dayOfWeek === 0 || dayOfWeek === 6) {
    return true;
  }
  // 这里可以添加法定节假日的判断逻辑，比如判断特定的日期是否是法定节假日
  return false;
}
</script>

<style>
.count{
  display: flex;
  justify-content: space-between;
}
.attendanceClass.el-table--default .cell {
  padding: 0 !important;
}
</style>